<template>
  <el-form ref="spuForm" :model="spuInfo" style="margin-top: 20px" :rules="rules">
    <el-form-item label="SPU名称" prop="spuName">
      <el-input v-model="spuInfo.spuName" style="width: 90%" />
    </el-form-item>
    <el-form-item label="SPU品牌" prop="tmId">
      <el-select v-model="spuInfo.tmId" placeholder="请选择SPU品牌">
        <el-option v-for="trademark in trademarkList" :key="trademark.id" :label="trademark.tmName" :value="trademark.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="品牌描述" prop="description">
      <el-input v-model="spuInfo.description" type="textarea" style="width: 90%" />
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        :class="{'spu-image-upload': spuImageList.length >= 3}"
        action="/dev-api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        accept="image/jpeg,image/png,image/jpg"
        :limit="3"
        :file-list="spuImageList"
      >
        <i class="el-icon-plus" />
        <div slot="tip" class="el-upload__tip" style="margin-left:70px;">
          只能上传jpg/png文件，且不超过2M
        </div>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img style="width:100px" width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
    <el-form-item label="销售属性" prop="spuSaleAttrList" label-width="80px">
      <el-select v-model="spuInfo.spuSaleAttr" :placeholder="`还剩下${formatBaseSaleAttrList.length}个属性`">
        <el-option v-for="baseSaleAttr in formatBaseSaleAttrList" :key="baseSaleAttr.id" :label="baseSaleAttr.name" :value="baseSaleAttr.name" />
      </el-select>
      <el-button style="margin-left:10px" type="primary" icon="el-icon-plus" :disabled="!spuInfo.spuSaleAttr" @click="addSpuSaleAttr">添加销售属性值</el-button>
      <el-table
        v-loading="loading"
        :data="spuInfo.spuSaleAttrList"
        border
        style="margin-top: 10px"
      >
        <el-table-column type="index" label="序号" align="center" width="60" />
        <el-table-column prop="saleAttrName" label="属性名" width="180" />
        <el-table-column label="属性值列表" prop="description">
          <template v-slot="{row}">
            <el-tag
              v-for="tag,index in row.spuSaleAttrValueList"
              :key="tag.saleAttrValueName"
              closable
              :disable-transitions="false"
              @close="handleClose(row, index)"
            >
              {{ tag.saleAttrValueName }}
            </el-tag>
            <el-input
              v-if="row.inputVisible"
              ref="saveTagInput"
              v-model="inputValue"
              class="input-new-tag"
              size="small"
              @keyup.enter.native="handleInputConfirm(row)"
              @blur="handleInputConfirm(row)"
            />
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              type="primary"
              @click="showInput(row)"
            >+ 添加属性值</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{$index}">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteSpuSaleAttr($index)" />
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item style="margin-left:80px;">
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="$emit('update:visible', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { reqGetAllTrademarkList } from '@/api/product/trademark'
import {
  reqGetBaseSaleAttrList,
  reqSaveSpuInfo,
  reqGetSpuImageList, // 根据spuId来获取所有的图片列表
  reqGetSpuSaleAttrList, // 根据SpuId来获取所有的销售属性
  reqUpdateSpuInfo // 更新spu
} from '@/api/product/spu.js'
import { mapState } from 'vuex'
export default {
  name: 'SaveSpu',
  props: {
    currentSpuInfo: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    const spuImageListValidate = (rule, value, callback) => {
      console.log('value', value)
      if (!value.length) {
        callback('请至少上传一张图片')
        return
      }
      callback()
    }
    const spuSaleAttrListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个销售属性')
        return
      }
      if (value.some((item) => item.spuSaleAttrValueList.length === 0)) {
        // console.log(1)
        callback('销售属性值不能为空')
        return
      }
      callback()
    }
    return {
      loading: false,
      spuList: [],
      trademarkList: [], // 品牌数据
      baseSaleAttrList: [], // 基本销售属性
      dialogImageUrl: '',
      dialogVisible: false,
      inputValue: '', // 新添加的属性值
      spuImageList: [],
      spuInfo: {
        spuSaleAttr: '', // 收集选中的属性
        spuName: '', // spu名称
        tmId: '', // 品牌ID
        description: '', // spu描述
        spuImageList: [], // 上传的图片列表
        spuSaleAttrList: [], // 销售属性列表
        category3Id: '', // 三级id
        ...this.currentSpuInfo
      },
      rules: {
        // spu名称
        spuName: [
          { required: true, message: '请输入SPU名称', trigger: 'blur' }
        ],
        // 品牌
        tmId: [{ required: true, message: '请选择品牌' }],
        // 描述
        description: [
          { required: true, message: '请输入SPU描述', trigger: 'blur' }
        ],
        // 销售属性列表
        spuSaleAttrList: [
          {
            required: true,
            validator: spuSaleAttrListValidate,
            trigger: 'blur'
          }
        ],
        // 上传的图片列表
        spuImageList: [
          {
            required: true,
            validator: spuImageListValidate,
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    // 过滤已选基本销售属性
    formatBaseSaleAttrList() {
      return this.baseSaleAttrList.filter(baseSaleAttr => {
        return !this.spuInfo.spuSaleAttrList.find(item => item.saleAttrName === baseSaleAttr.name)
      })
    },
    ...mapState('category', ['category3Id'])
    // 格式化图片
    // formatSpuImageList() {
    //   return this.spuInfo.spuImageList.map(item => ({
    //     name: item.imgName,
    //     url: item.imgUrl
    //   }))
    // }
  },
  async mounted() {
    try {
      const { id } = this.spuInfo
      let promises = [reqGetAllTrademarkList(), reqGetBaseSaleAttrList()]
      if (id) {
        promises = promises.concat([
          reqGetSpuImageList(id),
          reqGetSpuSaleAttrList(id)
        ])
      }
      const [
        responseTrademarkList,
        responseBaseSaleAttrList,
        responseSpuImageList,
        responseSpuSaleAttrList
      ] = await Promise.all(promises)
      this.trademarkList = responseTrademarkList.data
      this.baseSaleAttrList = responseBaseSaleAttrList.data
      if (responseSpuImageList && responseSpuImageList.code === 200) {
        this.spuImageList = responseSpuImageList.data
        this.spuImageList = this.spuImageList.map(item => ({
          name: item.imgName,
          url: item.imgUrl
        }))
        this.spuInfo.spuSaleAttrList = responseSpuSaleAttrList.data
      }
    } catch (e) {
      this.$message.error('获取品牌和销售属性数据失败...')
    }
  },
  methods: {
    // 3.删除spu属性
    deleteSpuSaleAttr(index) {
      this.spuInfo.spuSaleAttrList.splice(index, 1)
    },
    // 2.添加spu属性
    addSpuSaleAttr() {
      const id = this.baseSaleAttrList.find(item => item.name === this.spuInfo.spuSaleAttr).id
      const spuSaleAttrList = this.spuInfo.spuSaleAttrList
      if (!spuSaleAttrList.every(item => item.spuSaleAttrValueList.length !== 0)) {
        return this.$message.error('请添加具体属性值')
      }
      this.spuInfo.spuSaleAttrList.push({
        baseSaleAttrId: id,
        saleAttrName: this.spuInfo.spuSaleAttr,
        spuSaleAttrValueList: [],
        inputVisible: false // 控制当前对象所在行的按钮和输入框
      })
      this.spuInfo.spuSaleAttr = '' // 清空下拉列表

      // 清掉校验规则
      this.$refs.spuForm.clearValidate(['spuSaleAttrList'])
    },
    // 1.添加spu
    submitForm() {
      this.$refs.spuForm.validate(async(valid) => {
        if (valid) {
          this.spuInfo.category3Id = this.category3Id
          this.spuInfo.spuImageList = this.spuImageList.map((item) => {
            return {
              imgName: item.name,
              imgUrl: (item.response && item.response.data) || item.url
            }
          })
          if (!this.spuImageList.length) {
            this.$message.error('请选择至少一张图片...')
            return
          }
          const { id } = this.spuInfo
          let res
          if (id) {
            res = await reqUpdateSpuInfo(this.spuInfo)
          } else {
            res = await reqSaveSpuInfo(this.spuInfo)
          }
          // console.log(result);
          if (res.code === 200) {
            this.$message.success(` ${this.spuInfo.id ? '更新' : '添加'}SPU成功`)
            // 跳转回spu列表页
            this.$emit('update:visible', 1)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除图片时触发的函数
    handleRemove(file, fileList) {
      console.log(file, fileList)
      // fileList是存储剩余图片的数组
      this.spuImageList = fileList
    },
    // 选择完了图片并实现预览时触发的函数
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 上传图片成功后会触发的函数
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.spuImageList.push(file)
      this.$refs.spuForm.clearValidate(['spuImageList'])
    },
    // 图片上传前触发的函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    // 标签相关的内容
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1)
    },
    showInput(row) {
      // row.inputVisible = true
      this.$set(row, 'inputVisible', true)
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加了输入值之后，失去焦点后的效果
    handleInputConfirm(row) {
      const inputValue = this.inputValue
      const id = this.baseSaleAttrList.find(baseSaleAttr => baseSaleAttr.name === row.saleAttrName).id
      if (row.spuSaleAttrValueList.find(item => item.saleAttrValueName === inputValue)) {
        this.$message.error('属性值已存在，请换一个')
        row.inputVisible = false
        this.inputValue = ''
        return
      }
      if (inputValue) {
        // this.dynamicTags.push(inputValue);
        // row.spuSaleAttrValueList.push(inputValue)
        row.spuSaleAttrValueList.push({
          baseSaleAttrId: id, // 销售属性对应的id
          saleAttrName: row.saleAttrName, // 所属的销售属性 ，比如颜色 规格  尺寸
          saleAttrValueName: inputValue // 详细的属性值 比如颜色中的红色  蓝色  紫色
        })
      }
      row.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
